/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.cms.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.JsonResult;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.ReadExcel;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Record_product;
import com.thinkgem.jeesite.modules.cms.entity.Record_summary;
import com.thinkgem.jeesite.modules.cms.entity.Record_task;
import com.thinkgem.jeesite.modules.cms.entity.Task;
import com.thinkgem.jeesite.modules.cms.entity.taskData;
import com.thinkgem.jeesite.modules.cms.service.RecordService_product;
import com.thinkgem.jeesite.modules.cms.service.RecordService_summary;
import com.thinkgem.jeesite.modules.cms.service.RecordService_task;
import com.thinkgem.jeesite.modules.cms.service.TaskService;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 子任务管理Controller
 * 
 * @author leo
 * @version 2017-02-14
 */
//@Controller
@RequestMapping(value = "${adminPath}/cms/task")
public class TaskController extends BaseController {

	//@Autowired
	private TaskService taskService ;//???
	
	@Autowired
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}
	@Autowired
	public TaskService getTaskService() {
		if (taskService == null	)
			taskService = new 	TaskService();
		return taskService;
	}

	@Autowired
	private RecordService_task record_taskService;
	@Autowired
	private RecordService_product record_productService;
	@Autowired
	private RecordService_summary record_summaryService;

	@ModelAttribute
	public Task get(@RequestParam(required = false) String id) {
		Task entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = taskService.get(id);
		}
		if (entity == null) {
			entity = new Task();
		}
		return entity;
	}

	@RequiresPermissions("cms:task:view")
	@RequestMapping(value = { "list", "" })
	public String list(Task task, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<Task> page = taskService.findPage(
				new Page<Task>(request, response), task);
		model.addAttribute("page", page);
		return "modules/cms/taskList";
	}

	@RequiresPermissions("cms:task:view")
	@RequestMapping(value = "form")
	public String form(Task task, Model model) {
		model.addAttribute("task", task);
		return "modules/cms/taskForm";
	}

	@RequiresPermissions("cms:task:edit")
	@RequestMapping(value = "save")
	public String save(Task task, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, task)) {
			return form(task, model);
		}
		taskService.save(task);
		addMessage(redirectAttributes, "保存信息成功");

		return "redirect:" + this.adminPath + "/cms/task/?repage";
	}

	@RequestMapping({ "clear" })
	public String clear(@RequestParam Map<String, Object> paramMap,
			Model model, HttpServletRequest request) {
		Date endDate = DateUtils.parseDate(paramMap.get("endDate"));
		if (endDate == null) {
			model.addAttribute("message", "请选择终止日期");
			return "modules/cms/taskClear";
		}
		String end = DateUtils.formatDate(endDate,
				new Object[] { "yyyy-MM-dd" });
		this.taskService.clear(end);
		model.addAttribute("message", "删除成功");
		LogUtils.saveLog(request, "删除" + end + "数据");
		paramMap.put("endDate", end);
		model.addAttribute("paramMap", paramMap);
		return "modules/cms/taskClear";
	}

	@RequiresPermissions("cms:task:edit")
	@RequestMapping(value = "delete")
	public String delete(Task task, RedirectAttributes redirectAttributes) {
		taskService.delete(task);
		addMessage(redirectAttributes, "删除信息成功");
		return "redirect:" + Global.getAdminPath() + "/cms/task/?repage";
	}

	@RequestMapping({ "selectList" })
	public String selectList(Task task, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		list(task, request, response, model);
		return "modules/cms/taskSelectList";
	}

	@RequestMapping(value = { "/insert" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult insert(HttpServletRequest request,
			HttpServletResponse response) {
		JsonResult result = new JsonResult();

		String keyfield = request.getParameter("keyfield");
		if ((keyfield == null) || (keyfield.equals(""))) {
			result.setRet_code(-1);
			result.setErr_msg("缺少关键字段keyfield");
		} else {
			Task task = this.taskService.getByKeyfield2(keyfield);
			if (task != null) {
				result.setRet_code(-1);
				result.setErr_msg("主键重复");
			} else {
				Enumeration enu = request.getParameterNames();
				Task data = new Task();
				while (enu.hasMoreElements()) {
					String paraName = (String) enu.nextElement();
					getParamValue(data, paraName,
							request.getParameter(paraName));
				}
				this.taskService.save(data);
				result.setRet_code(0);
				Task task2 = this.taskService.getByKeyfield2(keyfield);
				result.setData(task2);
			}
		}
		return result;
	}

	private void getParamValue(Task task, String paramKey, String value) {
		if (paramKey.equals("keyfield")) {
			task.setKeyfield(value);
		}
		if (paramKey.equals("productid")) {
			task.setProductid(value);
		}
		if (paramKey.equals("productname")) {
			task.setProductname(value);
		}
		if (paramKey.equals("opdesc")) {
			task.setOpdesc(value);
		}
		if (paramKey.equals("dptask")) {
			task.setDptask(value);
		}
		if (paramKey.equals("dept")) {
			task.setDept(value);
		}
		if (paramKey.equals("pdate")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			try {
				Date pdate = sdf.parse(value);
				task.setPdate(pdate);
				task.setPdate_year(pdate.getYear());
				task.setPdate_month(pdate.getMonth());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (paramKey.equals("enddate")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			try {
				Date pdate = sdf.parse(value);
				task.setEnddate(pdate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (paramKey.equals("A")) {
			task.setA(Double.parseDouble(value));
		}
		if (paramKey.equals("B")) {
			task.setB(Double.parseDouble(value));
		}
		if (paramKey.equals("C")) {
			task.setC(Double.parseDouble(value));
		}
		if (paramKey.equals("D")) {
			task.setD(Double.parseDouble(value));
		}
		if (paramKey.equals("E")) {
			task.setE(Double.parseDouble(value));
		}
		if (paramKey.equals("F")) {
			task.setF(Double.parseDouble(value));
		}
		if (paramKey.equals("G")) {
			task.setG(Double.parseDouble(value));
		}
		if (paramKey.equals("H")) {
			task.setH(Double.parseDouble(value));
		}
		if (paramKey.equals("tasktype")) {
			task.setTasktype(value);
		}
		if (paramKey.equals("istaskcomplete")) {
			task.setIstaskcomplete(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("istagprocess")) {
			task.setIstagprocess(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("ispartcomplete")) {
			task.setIspartcomplete(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("isqctask")) {
			task.setIsqctask(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("isok")) {
			task.setIsok(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("isstart")) {
			task.setIsstart(value.toLowerCase().equals("true"));
		}
		if (paramKey.equals("userid")) {
			task.setUserid(value);
		}
		if (paramKey.equals("character01")) {
			task.setCharacter01(value);
		}
		if (paramKey.equals("character02")) {
			task.setCharacter02(value);
		}
		if (paramKey.equals("character03")) {
			task.setCharacter03(value);
		}
		if (paramKey.equals("character04")) {
			task.setCharacter04(value);
		}
		if (paramKey.equals("character05")) {
			task.setCharacter05(value);
		}
		if (paramKey.equals("character06")) {
			task.setCharacter06(value);
		}
		if (paramKey.equals("partnum")) {
			task.setPartnum(value);
		}
		if (paramKey.equals("commenttext")) {
			task.setCommenttext(value);
		}
		if (paramKey.equals("opcode")) {
			task.setOpcode(value);
		}
		if (paramKey.equals("jcdept")) {
			task.setJcdept(value);
		}
		if (paramKey.equals("number03")) {
			task.setNumber03(value);
		}
		if (paramKey.equals("number07")) {
			task.setNumber07(value);
		}
		if (paramKey.equals("number13")) {
			task.setNumber13(value);
		}
		if (paramKey.equals("starhour")) {
			task.setStarhour(value);
		}
		if (paramKey.equals("prodcode")) {
			task.setProdcode(value);
		}
		if (paramKey.equals("xpartnum")) {
			task.setXpartnum(value);
		}
	}

	@RequestMapping({ "upload" })
	public String upload(HttpServletRequest request,
			HttpServletResponse response) {
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = mulRequest.getFile("filename");
		String filename = file.getOriginalFilename();
		if ((filename == null) || ("".equals(filename))) {
			return null;
		}
		String path = request.getSession().getServletContext()
				.getRealPath("upload/excel");
		File targetFile = new File(path, filename);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			List<List<Object>> objs = ReadExcel.readExcel(targetFile);
			for (int i = 1; i < objs.size(); i++) {
				Task data = new Task();
				data.setKeyfield(((List) objs.get(i)).get(0).toString());
				data.setProductid(((List) objs.get(i)).get(1).toString());
				data.setProductname(((List) objs.get(i)).get(2).toString());
				data.setOpdesc(((List) objs.get(i)).get(3).toString());
				data.setDptask(((List) objs.get(i)).get(4).toString());
				data.setDept(((List) objs.get(i)).get(5).toString());
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat sdf_year = new SimpleDateFormat("yyyy");
				Date pdate = sdf.parse(((List) objs.get(i)).get(6).toString());
				Calendar mCalendar = Calendar.getInstance();
				mCalendar.setTime(pdate);
				data.setPdate(pdate);
				data.setPdate_year(Integer.parseInt(sdf_year.format(pdate)));
				data.setPdate_month(mCalendar.get(2) + 1);
				data.setA(Double.parseDouble(((List) objs.get(i)).get(7).toString()));
				data.setB(Double.parseDouble(((List) objs.get(i)).get(7+1).toString()));
				data.setC(Double.parseDouble(((List) objs.get(i)).get(7+2).toString()));
				data.setD(Double.parseDouble(((List) objs.get(i)).get(7+3).toString()));
				data.setE(Double.parseDouble(((List) objs.get(i)).get(7+4).toString()));
				data.setF(Double.parseDouble(((List) objs.get(i)).get(7+5).toString()));
				data.setG(Double.parseDouble(((List) objs.get(i)).get(7+6).toString()));
				data.setH(Double.parseDouble(((List) objs.get(i)).get(7+7).toString()));
				data.setTasktype(((List) objs.get(i)).get(8+7).toString());
				data.setIstaskcomplete(Boolean.parseBoolean(((List) objs.get(i))
						.get(9+7).toString()));
				data.setIstagprocess(Boolean.parseBoolean(((List) objs.get(i))
						.get(10+7).toString()));
				data.setIspartcomplete(Boolean.parseBoolean(((List) objs.get(i))
						.get(11+7).toString()));
				data.setIsqctask(Boolean.parseBoolean(((List) objs.get(i)).get(
						12+7).toString()));
				data.setIsok(Boolean.parseBoolean(((List) objs.get(i)).get(13+7)
						.toString()));
				data.setIsstart(Boolean.parseBoolean(((List) objs.get(i)).get(
						14+7).toString()));
				data.setUserid(((List) objs.get(i)).get(15+7).toString());
				data.setCharacter01(((List) objs.get(i)).get(16+7).toString());
				data.setCharacter02(((List) objs.get(i)).get(17+7).toString());
				data.setCharacter03(((List) objs.get(i)).get(18+7).toString());
				data.setCharacter04(((List) objs.get(i)).get(19+7).toString());
				data.setCharacter05(((List) objs.get(i)).get(20+7).toString());
				data.setCharacter06(((List) objs.get(i)).get(21+7).toString());
				data.setPartnum(((List) objs.get(i)).get(22+7).toString());
				data.setCommenttext(((List) objs.get(i)).get(23+7).toString());
				data.setProdcode(((List) objs.get(i)).get(24+7).toString());
				data.setJcdept(((List) objs.get(i)).get(25+7).toString());
				data.setNumber03(((List) objs.get(i)).get(26+7).toString());
				data.setNumber07(((List) objs.get(i)).get(27+7).toString());
				data.setNumber13(((List) objs.get(i)).get(28+7).toString());
				data.setOpcode(((List) objs.get(i)).get(29+7).toString());
				data.setStarhour(((List) objs.get(i)).get(30+7).toString());
				data.setXpartnum(((List) objs.get(i)).get(31+7).toString());

				this.taskService.save(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:" + this.adminPath + "/cms/task";
	}

	@RequestMapping(value = { "/getNoComplete" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getNoComplete() {
		JsonResult result = new JsonResult();
		List<Task> tasks = this.taskService.getNoEnd();
		result.setData(tasks);
		if (tasks != null) {
			result.setRet_code(0);
		} else {
			result.setRet_code(-1);
		}
		return result;
	}

	@RequestMapping(value = { "/updateComplete" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult updateComplete(String keyfield) {
		JsonResult result = new JsonResult();

		int count = this.taskService.partcomplete(keyfield);

		result.setRet_code(0);
		result.setErr_msg(count > 0 ? "" : "更新条数0");
		return result;
	}

	@RequestMapping(value = { "/getTask2" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getTask2(String keyfield) {
		JsonResult result = new JsonResult();
		Task task = this.taskService.getByKeyfield2(keyfield);
		result.setData(task);
		if (task != null) {
			result.setRet_code(0);
		} else {
			result.setRet_code(-1);
		}
		return result;
	}

	@RequestMapping(value = { "/getTask" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getTask(String keyfield) {
		JsonResult result = new JsonResult();
		taskData task = this.taskService.getByKeyfield(keyfield);
		result.setData(task);
		if (task != null) {
			result.setRet_code(0);
		} else {
			result.setRet_code(-1);
		}
		return result;
	}

	@RequestMapping(value = { "/getProduct" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getProduct(String productid) {
		JsonResult result = new JsonResult();
		taskData task = this.taskService.getByProductid(productid);
		result.setData(task);
		if (task != null) {
			result.setRet_code(0);
		} else {
			result.setRet_code(-1);
		}
		return result;
	}

	@RequestMapping(value = { "/start" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult start(String keyfield, String userid, int force) {
		JsonResult result = new JsonResult();
		if (force == 0) {
			taskData td = this.taskService.getByKeyfield(keyfield);
			if (td.getIsstart()) {
				result.setRet_code(1);
				result.setErr_msg("有开工记录，是否需要继续开工?");
			} else {
				this.taskService.start(keyfield, userid);
				Record_task record = new Record_task();
				Date date = new Date();

				record.setKeyfield(keyfield);
				record.setDate(date);
				record.setTime(date);
				record.setType("S");
				record.setUserid(userid);
				record.setDescription(userid + "-开工");
				this.record_taskService.save(record);

				result.setRet_code(0);
			}
		} else {
			this.taskService.start(keyfield, userid);
			Record_task record = new Record_task();
			Date date = new Date();

			record.setKeyfield(keyfield);
			record.setDate(date);
			record.setTime(date);
			record.setType("S");
			record.setUserid(userid);
			record.setDescription(userid + "-开工");
			this.record_taskService.save(record);

			result.setRet_code(0);
		}
		return result;
	}

	@RequestMapping(value = { "/complete" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult complete(String keyfield, String userid, int update) {
		JsonResult result = new JsonResult();
		taskData td = this.taskService.getByKeyfield(keyfield);
		if (!td.getIsstart()) {
			result.setRet_code(1);
			result.setErr_msg("记录还未开工");
		} else {
			if (update == 1) {
				this.taskService.complete(keyfield, userid);
			} else {
				this.taskService.qcComplete(keyfield);
			}
			Record_task record = new Record_task();
			Date date = new Date();

			record.setKeyfield(keyfield);
			record.setDate(date);
			record.setTime(date);
			record.setType("E");
			record.setUserid(userid);
			record.setDescription(userid + "-完工");
			this.record_taskService.save(record);

			result.setRet_code(0);
		}
		return result;
	}

	@RequestMapping(value = { "/uploadrecord" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult uploadrecord(String keyfield, String userid, String src) {
		JsonResult result = new JsonResult();
		Record_task record = new Record_task();
		Date date = new Date();

		record.setKeyfield(keyfield);
		record.setDate(date);
		record.setTime(date);
		record.setType("P");
		record.setUserid(userid);
		record.setDescription(src);
		this.record_taskService.save(record);

		result.setRet_code(0);

		return result;
	}

	@RequestMapping(value = { "/back" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult back(String keyfield, String userid, String reason) {
		JsonResult result = new JsonResult();

		this.taskService.back(keyfield, userid);
		Record_task record = new Record_task();
		Date date = new Date();

		record.setKeyfield(keyfield);
		record.setDate(date);
		record.setTime(date);
		record.setType("QC");
		record.setUserid(userid);
		record.setDescription(reason);
		this.record_taskService.save(record);

		result.setRet_code(0);

		return result;
	}

	@RequestMapping(value = { "/productok" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult productok(String productid, String reason, String userid) {
		JsonResult result = new JsonResult();

		this.taskService.updateProduct(productid, 1);
		Record_product record = new Record_product();
		Date date = new Date();

		record.setProductid(productid);
		record.setDate(date);
		record.setTime(date);
		record.setIsok(1);
		record.setUserid(userid);
		record.setDescription(reason);
		this.record_productService.save(record);

		result.setRet_code(0);

		return result;
	}

	@RequestMapping(value = { "/productnotok" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult productnotok(String productid, String reason,
			String userid) {
		JsonResult result = new JsonResult();
		if (this.taskService.hasStart(productid)) {
			this.taskService.updateProduct(productid, 0);
			Record_product record = new Record_product();
			Date date = new Date();

			record.setProductid(productid);
			record.setDate(date);
			record.setTime(date);
			record.setIsok(0);
			record.setUserid(userid);
			record.setDescription(reason);
			this.record_productService.save(record);

			result.setRet_code(0);
		} else {
			result.setRet_code(-1);
			result.setErr_msg("任务已开工，无法进行不合格操作");
		}
		return result;
	}

	@RequestMapping(value = { "/getYeardata" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getYeardata(String userid) {
		JsonResult result = new JsonResult();
		if (userid.equals("")) {
			result.setRet_code(-1);
		} else {
			result.setData(this.taskService.getYeardata(userid));
			result.setRet_code(0);
		}
		return result;
	}

	@RequestMapping(value = { "/suredata" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult suredata(String userid, int month, int count, double gdp) {
		JsonResult result = new JsonResult();
		if ((userid.equals("")) || (month < 1) || (month > 12)) {
			result.setRet_code(-1);
		} else {
			Record_summary record = new Record_summary();
			long time = System.currentTimeMillis();
			Calendar mCalendar = Calendar.getInstance();
			mCalendar.setTimeInMillis(time);

			Date date = new Date();
			record.setConfirmcount(count);
			record.setConfirmgdp(gdp);
			record.setConfirmyear(mCalendar.get(1));
			record.setConfirmmonth(month);
			record.setDate(date);
			record.setTime(date);
			record.setUserid(userid);
			this.record_summaryService.save(record);

			result.setRet_code(0);
		}
		return result;
	}

	@RequestMapping(value = { "/getMonthdata" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getMonthdata(String userid) {
		JsonResult result = new JsonResult();
		if (userid.equals("")) {
			result.setRet_code(-1);
		} else {
			result.setData(this.taskService.getMonthdata(userid));
			result.setRet_code(0);
		}
		return result;
	}

	@RequestMapping(value = { "/getDaydata" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JsonResult getDaydata(String userid) {
		JsonResult result = new JsonResult();
		if (userid.equals("")) {
			result.setRet_code(-1);
		} else {
			result.setData(this.taskService.getDaydata(userid));
			result.setRet_code(0);
		}
		return result;
	}
}